

function PageContextJqgrid(settings){
	PageContext.call(this, settings);
	var _this = this; //把this保存下来，以后用_this代替this，这样就不会被this弄晕了
	var grid_selector = "#"+_this.setting.tableId;
	var pager_selector = "#"+ _this.setting.tableId+"Pager";
	this.grid_selector = grid_selector;
	this.pager_selector = pager_selector;
	//表格-内容
	 var url = $("#"+_this.setting.formId).attr("action");
	 if(!url){
		return false; 
	 }
	 if(url.indexOf("?")>-1){
		 url+="&noPage="+!_this.setting.canPage;
	 }else{
		 url+="?noPage="+!_this.setting.canPage;
	 }
	 this.url = url;

	 var  edit_default_option = {
  		     keys : true,        //这里按[enter]保存  
             url: _this.setting.saveUrl,  
             mtype : "POST",  
             restoreAfterError: true,  
             extraparam: {  
             },  
//             oneditfunc: function(rowid){//开始编辑 
//                 console.log(rowid);  
//             },  
             successfunc: function(response){  
            	 console.log("edit_default_option successfunc")
            	 console.log(response)
                 return true;  
             },  
             errorfunc: function(rowid, res){  
                 console.log(rowid);  
                 console.log(res);  
             }  
  	   };
	 var delete_default_option = {
		    url : _this.setting.deleteUrl,
			mtype : "POST",
			reloadAfterSubmit: false,
			beforeShowForm: null,
			beforeInitData : null,
			afterShowForm: null,
			beforeSubmit: null,
			onclickSubmit: null,
			afterSubmit: null,
			delData:{tableId:$("#tableId").val()},
			
	 };
	var defult = {
			url:url,
			datatype: "json",//
			height: 260,
			rownumbers: true,
			viewrecords : true,
			rowNum:10,
			rowList:[10,20,30],
			pager : pager_selector,
			altRows: true,
			delOptions:delete_default_option,
			editOptions:edit_default_option,
			multiselect: true,
			//multikey: "ctrlKey",
	        multiboxonly: true,
	        shrinkToFit:true,
			autowidth:true,
			loadComplete : function() {
				var table = this;
				if(!pageContext.setting.canUpdate){
					$("#"+pageContext.setting.tableId+" tr td .ui-inline-edit").remove();
				}
				setTimeout(function(){
					styleCheckbox(table);
					
					updateActionIcons(table);
					updatePagerIcons(table);
					enableTooltips(table);
				}, 0);
			},
			gridComplete:function(){
			},
			editurl: _this.setting.saveUrl //nothing is saved 
		};
	/**
	 * 当前页面上下文
	 */
	this.formInit = function(layero){
		 
	}//更新后操作
	this.updateItemAfter = function(result,para){
		 
	 };
	 this.addItemAfter = function(result,para){
		 
	 }; 
	  
	 this.init = function(option){//初始化
		    option = $.extend( true,  {}, defult, option || {}); 
		    jQuery(grid_selector).jqGrid(option);
		    
			setTimeout(function(){
				//navButtons
				jQuery(grid_selector).jqGrid('navGrid',pager_selector,
					{ 	//navbar options
						edit: false,
						editicon : 'ace-icon fa fa-pencil blue',
						add: false,
						addicon : 'ace-icon fa fa-plus-circle purple',
						del: false,
						delicon : 'ace-icon fa fa-trash-o red',
						search: true,
						searchicon : 'ace-icon fa fa-search orange',
						refresh: false,
						refreshicon : 'ace-icon fa fa-refresh green',
						view: false,
						viewicon : 'ace-icon fa fa-search-plus grey',
//						searchfunc:searchfunc,
					},
					{
						//edit record form
						//closeAfterEdit: true,
						//width: 700,
						recreateForm: true,
						beforeShowForm : function(e) {
							var form = $(e[0]);
							form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
							style_edit_form(form);
						}
					},
					{
						//new record form
						//width: 700,
						closeAfterAdd: true,
						recreateForm: true,
						viewPagerButtons: false,
						beforeShowForm : function(e) {
							var form = $(e[0]);
							form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
							.wrapInner('<div class="widget-header" />')
							style_edit_form(form);
						}
					},
					{
						//delete record form
						recreateForm: true,
						beforeShowForm : function(e) {
							var form = $(e[0]);
							if(form.data('styled')) return false;
							
							form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
							style_delete_form(form);
							
							form.data('styled', true);
						},
						onClick : function(e) {
							//alert(1);
						}
					},
					{
						//search form
						recreateForm: true,
						afterShowSearch: function(e){
							var form = $(e[0]);
							form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
							style_search_form(form);
						},
						afterRedraw: function(){
							style_search_filters($(this));
						}
						,
						multipleSearch: true,
						/***/
						multipleGroup:false,//子查询
						showQuery: false
						
					},
					{
						//view record form
						recreateForm: true,
						beforeShowForm: function(e){
							var form = $(e[0]);
							form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
						}
					} 
				);
			},0);
		    //页面初始化
	 		_this.initEvent();
	 		_this.initEventOther();
	 }
	 this.initEventOther = function(){
		 //工具栏- 
		 $(".toolbar .bestsearchBtn").on("click",function(e){
			 e.preventDefault();
			 var options = {};
			 $("#search_"+_this.setting.tableId).click();
			 return false;
		 });
		    //resize to fit page size
			$(window).on('resize.jqGrid', function () {
				$(grid_selector).jqGrid( 'setGridWidth', $(".page-content").width() );
		    })
			//resize on sidebar collapse/expand
			var parent_column = $(grid_selector).closest('[class*="col-"]');
			$(document).on('settings.ace.jqGrid' , function(ev, event_name, collapsed) {
				if( event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed' ) {
					//setTimeout is for webkit only to give time for DOM changes and then redraw!!!
					setTimeout(function() {
						$(grid_selector).jqGrid( 'setGridWidth', parent_column.width() );
					}, 0);
				}
		    })
			$(grid_selector).jqGrid( 'setGridHeight', $(document).height()-60-$(pager_selector).height()-$("#condition").height()-$("#breadcrumbs").height() );
			pageInit();
//			$(".ui-jqgrid-htable").css("border-collapse","collapse")
			$(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size
	 		$("#"+_this.setting.formId).validationEngine('attach', {promptPosition : "topLeft", autoPositionUpdate : true});
	 		$(document).one('ajaxloadstart.page', function(e) {
				$(grid_selector).jqGrid('GridUnload');
				$('.ui-jqdialog').remove();
			});
	 }
	 this.getCheckedIds = function() {//获取表格选中的id
//		 var ids = $(grid_selector).jqGrid('getGridParam','selarrrow');
//		 console.log(ids)
		 var ids = [];
		 var check = $(grid_selector).find("tr td").find("input.cbox");
		 if(check){
			 check.each(function(){
				 if(this.checked){
					 ids.push($(this).closest("tr").attr("id"));
				 }
			 })
		 }
		 console.log(ids)
		 return ids.join(",");
	 };
	 this.getCheckedRecords = function() {//获取表格选中的项
		 var ids = [];
		 var check = $(grid_selector).find("tr td").find("input.cbox");
		 if(check){
			 check.each(function(){
				 if(this.checked){
					 ids.push($(this).closest("tr"));
				 }
			 })
		 }
		 return check;
	 } 
	 this.deleteItemAfter = function(ids){
		 _this.search();
	}
	this.removeItemAfter=function(id){
		 
	 };
	 this.updateItem = function(para,option){//更新

	 }
	 this.deleteItem = function(index,option){//删除
		 option = $.extend(true, delete_default_option, option || {});
		 $(grid_selector).jqGrid('delGridRow', index, option);
	 }
	 this.toAdd = function(option)  
	 {  
		var p = {};
		p.addRowParams = $.extend(true, edit_default_option, option || {});
		p = $(grid_selector).jqGrid("addRow", p);
		var newrowid = p[0].rowID;
		// 设置grid单元格可编辑
//		$(grid_selector).jqGrid('editRow', newrowid, option);
		$("#jCancelButton_" + newrowid).on("click", function() {
			if (_this.cancelCheck(this)) {
				var ind = $(grid_selector).jqGrid("getInd",newrowid,true);
				var editable = $(ind).attr("new");
				if("1"==editable){
					$(grid_selector).jqGrid('delRowData', newrowid);
				}
			}
		});
		var ind = $(grid_selector).jqGrid("getInd",newrowid,true);
		styleCheckbox($(ind));
		jQuery.fn.fmatter.rowactions
				.call($("#jEditButton_" + newrowid), 'edit',p);
		return;
		var selectedId = $(grid_selector).jqGrid("getGridParam", "selrow");
		var ids = jQuery(grid_selector).jqGrid('getDataIDs');
		// 获得当前最大行号（数据编号）
		var rowid = Math.max.apply(Math, ids);
		// 获得新添加行的行号（数据编号）
		var newrowid = rowid + 1;
		var dataRow = {};
		// 将新添加的行插入到第一列
		$(grid_selector).jqGrid("addRowData", newrowid, dataRow, "first");
		// 设置grid单元格不可编辑
		$(grid_selector).setGridParam({
			cellEdit : false
		});
		option = $.extend(true, edit_default_option, option || {});
		// 设置grid单元格可编辑
		$(grid_selector).jqGrid('editRow', newrowid, option);
		$("#jCancelButton_" + newrowid).on("click", function() {
			if (_this.cancelCheck(this)) {
				$(grid_selector).jqGrid('delRowData', newrowid);
			}
		});
		jQuery.fn.fmatter.rowactions
				.call($("#jEditButton_" + newrowid), 'edit');
	 }  
     this.toEdit = function(index,option){
    	 option = $.extend(true, edit_default_option,option||{} );
    	 //设置grid单元格可编辑  
  	    $(grid_selector).jqGrid('editRow', index,option);
  	   // jQuery.fn.fmatter.rowactions.call($("#jEditButton_"+index),'edit');
  		var ind = $(grid_selector).jqGrid("getInd",index,true);
		var oldid = $(ind).attr("oldid");
		if(oldid){
			$("#jEditButton_"+oldid).click();
		}else{
			$("#jEditButton_"+index).click();
		}
     }
	 this.cancelCheck = function(me){
		 return true;
	 }
	 this.getRowUpdatedData = function(ind){
		 var data = $('td[role="gridcell"] input,select,textarea,password',ind).fieldUpdatedSerializeMap();
		 return data;
	 }
	 this.getFilter = function(){
		 var para = $(grid_selector).jqGrid("getGridParam");
         var postData = {};
         postData = $.extend(true,{},postData,para.postData);
         return postData;
	 }
	 this.getFinalPara = function(){
		    var data = {  
			    }
			 var from = $("#"+_this.setting.formId);
			 if(from.validationEngine("validate")){
				 var searchParames = '' ; 
		         searchParames = from.formSerializeNotBlank();  
		         data.para = (searchParames)
			 }
			 data.filter = _this.getFilter() ;
			 return data;
	 }
	 this.search = function(){//搜索
	    var page = $(grid_selector).getGridParam('page'); // current page  
	    var rows = $(grid_selector).getGridParam('rowNum'); // rows    
	    var sidx = $(grid_selector).getGridParam('sidx'); // sidx  
	    var sord = $(grid_selector).getGridParam('sord'); // sord  
	    var data = {  
		        page:page,  
		        rows:rows,  
		        sidx:sidx,  
		        sord:sord  
		    }
		 var from = $("#"+_this.setting.formId);
		 if(from.validationEngine("validate")){
			 var searchParames = '' ; 
	         searchParames = from.formSerializeNotBlank();  
	         console.log(searchParames)
	         data.url = _this.url +"&"+searchParames;
	         console.log(data)
	         console.log(_this.getFilter());
//	         $(grid_selector).jqGrid("setGridParam",{postData:{filters:""}});
	         $("#fbox_" + _this.setting.tableId + "_reset").click();
	         jQuery(grid_selector).jqGrid('setGridParam',data,true).trigger("reloadGrid");  
	         var index = page *rows;
	         var len = (""+index+"").length;
	         var defaultW = 35;
	         if(len>3){
	        	 while(len>3){
	        		 defaultW+=5;
	        		 len--;
	        	 }
	         }
//	         console.log(defaultW)
//	         console.log($(".searchTable_rn").width());
//	         console.log($(".jqgrid-rownum").width());
//	         $(".searchTable_rn").width(defaultW);
//	         $(".jqgrid-rownum").width(defaultW);
		 }
	 } ;
	 
};
function searchfunc($t, pSearch){
	console.log($t);
	console.log(pSearch);
}

//switch element when editing inline
function aceSwitch( cellvalue, options, cell ) {
	setTimeout(function(){
		$(cell) .find('input[type=checkbox]')
			.addClass('ace ace-switch ace-switch-5')
			.after('<span class="lbl"></span>');
	}, 0);
}  
function pickDate( cellvalue, options, cell ) {
	setTimeout(function(){
		$(cell) .find('input[type=text]').on("click", function(){  
			WdatePicker({dateFmt:'yyyy-MM-dd'});
		 })
	}, 0);
}
function pickDateTime( cellvalue, options, cell ) {
	setTimeout(function(){
		$(cell) .find('input[type=text]').on("click", function(){  
			WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'});
		 })
	}, 0);
}
function pickTimestamp( cellvalue, options, cell ) {
	setTimeout(function(){
		$(cell) .find('input[type=text]').on("click", function(){  
			WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss.SSS'});
		 })
	}, 0);
}
function pickTime( cellvalue, options, cell ) {
	setTimeout(function(){
		$(cell) .find('input[type=text]').on("click", function(){  
			WdatePicker({dateFmt:'HH:mm:ss'});
		 })
	}, 0);
}
function style_edit_form(form) {
	//enable datepicker on "sdate" field and switches for "stock" field
	form.find('input[name=sdate]').datepicker({format:'yyyy-mm-dd' , autoclose:true})
	
	form.find('input[name=stock]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');
			   //don't wrap inside a label element, the checkbox value won't be submitted (POST'ed)
			  //.addClass('ace ace-switch ace-switch-5').wrap('<label class="inline" />').after('<span class="lbl"></span>');

			
	//update buttons classes
	var buttons = form.next().find('.EditButton .fm-button');
	buttons.addClass('btn btn-sm').find('[class*="-icon"]').hide();//ui-icon, s-icon
	buttons.eq(0).addClass('btn-primary').prepend('<i class="ace-icon fa fa-check"></i>');
	buttons.eq(1).prepend('<i class="ace-icon fa fa-times"></i>')
	
	buttons = form.next().find('.navButton a');
	buttons.find('.ui-icon').hide();
	buttons.eq(0).append('<i class="ace-icon fa fa-chevron-left"></i>');
	buttons.eq(1).append('<i class="ace-icon fa fa-chevron-right"></i>');		
}

function style_delete_form(form) {
	var buttons = form.next().find('.EditButton .fm-button');
	buttons.addClass('btn btn-sm btn-white btn-round').find('[class*="-icon"]').hide();//ui-icon, s-icon
	buttons.eq(0).addClass('btn-danger').prepend('<i class="ace-icon fa fa-trash-o"></i>');
	buttons.eq(1).addClass('btn-default').prepend('<i class="ace-icon fa fa-times"></i>')
}

function style_search_filters(form) {
	form.find('.delete-rule').val('X');
	form.find('.add-rule').addClass('btn btn-xs btn-primary');
	form.find('.add-group').addClass('btn btn-xs btn-success');
	form.find('.delete-group').addClass('btn btn-xs btn-danger');
}
function style_search_form(form) {
	var dialog = form.closest('.ui-jqdialog');
	var buttons = dialog.find('.EditTable')
	buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'ace-icon fa fa-retweet');
	buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'ace-icon fa fa-comment-o');
	buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'ace-icon fa fa-search');
}

function beforeEditCallback(e) {
	var form = $(e[0]);
	form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
	style_edit_form(form);
}



//it causes some flicker when reloading or navigating grid
//it may be possible to have some custom formatter to do this as the grid is being created to prevent this
//or go back to default browser checkbox styles for the grid
function styleCheckbox(table) {
	return;
	$(table).find('input:checkbox').addClass('ace ace-checkbox-2')
	.wrap('<label />')
	.after('<span class="lbl align-top" />')
	.on("click",function(){
		var ch = $(this).prev('input');
//		ch = this;
		console.log(this)
		console.log($(this).prop("checked"));
		$(this).closest("td").click();
		return ;
		if (!$(ch).prop("checked")) { 
			$(ch).prop("checked",true).attr("checked","checked")
		} else{
			$(ch).prop("checked",false).attr("checked","")
		}
//		$(ch).prop("checked",true).attr("checked",true)
	})
;

	$('.ui-jqgrid-labels th[id*="cb_"]:first-child')
	.find('input.cbox[type=checkbox]').addClass('ace')
	.wrap('<label />').after('<span class="lbl align-top" />').on("click",function(){
		alert()
	})
 
}


//unlike navButtons icons, action icons in rows seem to be hard-coded
//you can change them like this in here if you want
function updateActionIcons(table) {
 
	var replacement = 
	{
		'ui-ace-icon fa fa-pencil' : 'ace-icon fa fa-pencil blue',
		'ui-ace-icon fa fa-trash-o' : 'ace-icon fa fa-trash-o red',
		'ui-icon-disk' : 'ace-icon fa fa-check green',
		'ui-icon-cancel' : 'ace-icon fa fa-times red'
	};
	$(table).find('.ui-pg-div span.ui-icon').each(function(){
		var icon = $(this);
		var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
		if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
	})
	
}

//replace icons with FontAwesome icons like above
function updatePagerIcons(table) {
	var replacement = 
	{
		'ui-icon-seek-first' : 'ace-icon fa fa-angle-double-left bigger-140',
		'ui-icon-seek-prev' : 'ace-icon fa fa-angle-left bigger-140',
		'ui-icon-seek-next' : 'ace-icon fa fa-angle-right bigger-140',
		'ui-icon-seek-end' : 'ace-icon fa fa-angle-double-right bigger-140'
	};
	$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function(){
		var icon = $(this);
		var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
		
		if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
	})
}

function enableTooltips(table) {
	$('.navtable .ui-pg-button').tooltip({container:'body'});
	$(table).find('.ui-pg-div').tooltip({container:'body'});
}
